/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import React, { Component } from 'react';
import { Meteor } from 'meteor/meteor';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import DropZone from 'react-dropzone';
import { browserHistory } from 'react-router';
import { X509 } from 'jsrsasign';
import { Buffer } from 'buffer';
import { List, ListItem } from 'material-ui/List';
import Drawer from 'material-ui/Drawer';
import AppBar from 'material-ui/AppBar';
import baseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Subheader from 'material-ui/Subheader';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import Divider from 'material-ui/Divider';
import TextField from 'material-ui/TextField';
import Checkbox from 'material-ui/Checkbox';
import NavigationLeft from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import Snackbar from 'material-ui/Snackbar';
import Chip from 'material-ui/Chip';
import { red700, green700, blue400,blue300 } from 'material-ui/styles/colors';
import SvgIconCheck from 'material-ui/svg-icons/toggle/check-box';
import SvgIconErr from 'material-ui/svg-icons/alert/error';
import Avatar from 'material-ui/Avatar';
import moment from 'moment';

import repchain from '../api/repchainUtil'

const styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
    },
    toolbar: {
        position: 'fixed',
        top: 0,
        width: '100%',
    },
}


export default class RepchainUserRegister extends Component {
    constructor(props) {
        super(props);
        this.state = {
            import_open: true,
            import_cert_file_name: '',
            import_cert_b2s: '',

            check_user_info: false,
            after_check_user_info: false,

            snackbar_open: false,

            repchainRegisterUserTxid: '',
            repchainRegisterUserinfo: '',

            checkPass: false,
            pass_err: '',
            user_pass: '',
            confirmCertInfo: false,

            new_name: '',
            default_name:'',
            new_name_err: '',
            new_phone: '',
            default_phone:'',
            new_phone_err: '',
            new_email: '',
            default_email:'',
            new_email_err: '',
            new_address: '',
            default_address:'',
            new_address_err: '',
            new_unit: '',
            default_unit: '',
            new_unit_err: '',

        };
    }

    getChildContext() {
        return { muiTheme: getMuiTheme(baseTheme) };
    }

    componentWillUnmount(){
        this._isMounted = false;
    }

    setStateByCheck(po){
        if(this._isMounted){
            this.setState(po);
        }
    }

    componentWillMount(){
        this._isMounted = true;
        if (Session.get('curUser') === 'none'){
            browserHistory.push('/login');
        }else if(Session.get('isAdmin') == false ){
            browserHistory.push('/tab0')
        }
        if(!this.props.registerUser){
            this.setState({default_address:this.props.user_item.address,
            default_name:this.props.user_item.name,
            default_email:this.props.user_item.email,
            default_unit:this.props.user_item.unit,
            default_phone:this.props.user_item.phone,
            new_address:this.props.user_item.address,
            new_name:this.props.user_item.name,
            new_email:this.props.user_item.email,
            new_unit:this.props.user_item.unit,
            new_phone:this.props.user_item.phone})
        }
    }

    componentDidMount(x, y, z) {
        this.setState({ cw: window.innerWidth, ch: window.innerHeight });
    }

    onDropCertFile(acceptedFiles, failedFiles) {
        if (acceptedFiles.length == 0) {
            throw new Error("Import cert file failed!");
        }
        const cert_file = acceptedFiles[0];
        this.setState({ import_cert_file_name: cert_file.name, after_check_user_info: false });
        let fr = new FileReader();
        fr.onload = () => {
            const buf = new Buffer(fr.result);
            const buf_string = buf.toString('utf-8');
            this.setState({ import_cert_b2s: buf_string });
        }
        fr.onerror = () => {
            console.log('Error: import reading cert file failed!')
        }
        fr.readAsArrayBuffer(cert_file);
    }

    renderUserInfoCheck() {
        const { import_cert_b2s, check_user_info, after_check_user_info, snackbar_open, repchainRegisterUserinfo, checkPass } = this.state;

        if (check_user_info) {
            let userInfo={name:this.state.new_name,
                phone:this.state.new_phone,
                email:this.state.new_email,
                unit:this.state.new_unit,
                address:this.state.new_address,
            };
            const cert = new X509();
            cert.readCertPEM(import_cert_b2s);
            let str_format = cert.getNotBefore().toString().length == 13?'YYMMDDhhmmssZ':'YYYYMMDDhhmmssZ';
            userInfo['createdAt'] = cert.getNotBefore();

            return (
                <div id='user_info_check' style={{ height: this.state.ch, overflowY: 'auto', wordWrap: 'break-word' }}>
                    <AppBar title='审核证书'
                        style={styles.toolbar}
                        iconElementLeft={
                            <IconButton
                                onTouchTap={() => {
                                    this.setState({
                                        check_user_info: !this.state.check_user_info,
                                        import_open: !this.state.import_open
                                    })
                                }
                                }
                                iconStyle={{ width: 48, height: 48 }}
                                style={{ padding: 0 }}
                            >
                                <NavigationLeft />
                            </IconButton>
                        }>
                    </AppBar>
                    <h2 style={{ marginTop: 80, textAlign: 'center' }}>信息核对</h2>
                    <List style={{ margin: 15 }}>
                        <Subheader>用户基本信息</Subheader>
                        <ListItem primaryText={'姓名: ' + userInfo.name} />
                        <ListItem primaryText={'手机: ' + userInfo.phone} />
                        <ListItem primaryText={'邮箱: ' + userInfo.email} />
                        <ListItem primaryText={'工作单位: ' + userInfo.unit} />
                        <ListItem primaryText={'通讯地址: ' + userInfo.address} />
                        <ListItem primaryText={'日期: ' + moment(userInfo.createdAt.toString(),str_format).format('YYYY-MM-DD HH:mm:ss Z') } />
                    </List>
                    <List style={{ margin: 15 }}>
                        <Subheader>证书信息</Subheader>
                        <ListItem primaryText={'序列号: ' + cert.getSerialNumberHex()} />
                        <ListItem primaryText={'签名算法: ' + cert.getSignatureAlgorithmName()} />
                        <ListItem primaryText={'有效期至: ' + moment(cert.getNotAfter().toString(),str_format).format('YYYY-MM-DD HH:mm:ss Z')} />
                        <ListItem primaryText={'签名信息: ' + cert.getSignatureValueHex()} />
                    </List>
                    <Checkbox
                        label="信息校验完毕，正确无误！"
                        checked={after_check_user_info}
                        style={{ margin: 15, width: '90%' }}
                        onCheck={(event) => {
                            this.setState({ after_check_user_info: !after_check_user_info });
                        }}
                    />
                    <div style={{ textAlign: 'center' }}>

                        <RaisedButton
                            label="确认"
                            disabled={!after_check_user_info}
                            primary={after_check_user_info}
                            style={{ margin: 12 }}
                            onClick={(event) => {
                                this.setState({ checkPass: true })
                            }}
                        />
                        <RaisedButton
                            label="取消"
                            primary={true}
                            style={{ margin: 12 }}
                            onClick={(event) => {
                                this.setState({
                                    check_user_info: !this.state.check_user_info,
                                    import_open: !this.state.import_open
                                })
                            }}
                        />
                    </div>

                </div>
            );
        } else {
            return '';
        }

    }

    renderChip() {
        let avatar_color = this.state.repchainRegisterUserTxid == '' ? red700 : green700;
        let avatar_icon = this.state.repchainRegisterUserTxid == '' ? <SvgIconErr /> : <SvgIconCheck />;
        return (
            <Chip style={{ top: 25, }} onClick={() => {
                this.setState({ snackbar_open: false });
            }}>
                <Avatar color={avatar_color} icon={avatar_icon} />
                {this.state.repchainRegisterUserinfo}
            </Chip>
        );
    }

    render() {
        const { import_open, import_cert_file_name,
            check_user_info, snackbar_open,
            confirmCertInfo, user_pass, pass_err,
            checkPass, import_cert_b2s,
            new_name, default_name, new_name_err,
            new_phone, default_phone, new_phone_err,
            new_email, default_email, new_email_err,
            new_address, default_address, new_address_err,
            new_unit, default_unit, new_unit_err,
        } = this.state;
        const import_finished = import_cert_file_name != '' &&
            new_name_err == ''&& new_phone_err == '' &&
        new_email_err == '' && new_address_err == '' &&
        new_unit_err == '' && new_name != '' &&
        new_phone != '' && new_email != '' &&
        new_address != '' && new_unit != '';;
        const import_cert_border_style = import_cert_file_name != '' ? '1px dashed #46c121' : '1px dashed';
        const actions_import = [
            <RaisedButton
                label='确认'
                disabled={!import_finished}
                primary={import_finished}
                style={{ margin: 12 }}
                onClick={(event) => {
                    this.setState({ import_open: false, check_user_info: true });
                    console.log(event);

                }}
            />,
            <RaisedButton
                label='取消'
                primary={true}
                style={{ margin: 12 }}
                onClick={(event) => {
                    this.setState({ import_open: false });
                    this.props.handleChange(false);
                }}
            />
        ];
        let userInfo={name:this.state.new_name,
            phone:this.state.new_phone,
            email:this.state.new_email,
            unit:this.state.new_unit,
            address:this.state.new_address,
        };
        const actionCertInfo = [
            <FlatButton
                label="确认"
                primary={confirmCertInfo}
                disabled={!confirmCertInfo}
                onClick={(event) => {
                    if (this.props.registerUser) {
                        console.log("注册证书")
                        repchain.registerUserCertificate(new Buffer(import_cert_b2s).toString('base64'), userInfo, user_pass, Session.get('curUser').prv_key_pem_encrypted, Session.get('curUser').account_address, (err, result) => {
                            if (err) {
                                if (err.message.indexOf("已存在") > -1) {
                                    console.log(err.message);
                                    this.setState({ repchainRegisterUserinfo: "该证书已存在，请勿重复注册！" });
                                } else {
                                    this.setState({ repchainRegisterUserinfo: err.message });
                                    console.log(err);
                                }
                            } else {
                                this.setState({
                                    repchainRegisterUserinfo: "证书已提交，请等待确认！",
                                    repchainRegisterUserTxid: result
                                });
                                console.log(result);
                            }
                            this.setState({ snackbar_open: true });
                        });
                    } else {
                        console.log("修改证书！")
                        repchain.getAccountAddress(new Buffer(import_cert_b2s).toString('base64'), (err, res) => {
                            if(err){
                                this.setState({ repchainRegisterUserinfo: err.message});
                                this.setState({ checkPass: false, snackbar_open: true });
                            }else {
                                if(res != this.props.user_item.account_address){
                                    this.setState({ repchainRegisterUserinfo: "证书非该账户的证书，请重新选择证书！"});
                                    this.setState({ checkPass: false, snackbar_open: true });
                                }else{
                                    repchain.updateUserCertificate(new Buffer(import_cert_b2s).toString('base64'), userInfo,user_pass, Session.get('curUser').prv_key_pem_encrypted, Session.get('curUser').account_address, (err, result) => {
                                        if (err) {
                                            if (err.message.indexOf("已存在") > -1) {
                                                console.log(err.message);
                                                this.setState({ repchainRegisterUserinfo: "该证书已存在，请勿重复注册！" });
                                            } else {
                                                this.setState({ repchainRegisterUserinfo: err.message });
                                                console.log(err);
                                            }
                                        } else {
                                            this.setState({
                                                repchainRegisterUserinfo: "证书已提交，请等待确认！",
                                                repchainRegisterUserTxid: result
                                            });
                                            console.log(result);
                                        }
                                        this.setState({ checkPass: false, snackbar_open: true });
                                    });
                                }
                            }
                        })

                    }
                }}
            />,
            <FlatButton
                label="取消"
                primary={true}
                keyboardFocused={true}
                onClick={() => this.setState({ checkPass: false })}
            />
        ];
        return (
            <div>
                <Dialog
                    title='用户信息及证书'
                    actions={actions_import}
                    modal={false}
                    contentStyle={{ width: '94%' }}
                    open={import_open}
                    onRequestClose={(close) => {
                        this.setState({ import_open: close })
                    }}
                    autoScrollBodyContent={true}
                >
                    填写用户信息
                    <TextField
                    hintText='输入姓名'
                    errorText={new_name_err}
                    defaultValue={default_name}
                    floatingLabelText='姓名'
                    floatingLabelStyle={{color: blue300}}
                    fullWidth={true}
                    onChange={(e, newValue) => {
                        const name = newValue;
                        if (name === '')
                            this.setState({new_name: name, new_name_err: '姓名不可为空'});
                        else
                            this.setState({new_name: name, default_name:name, new_name_err: ''});
                    }}
                    />
                    <TextField
                    hintText='输入手机号，将作为您的私钥文件、证书文件名'
                    errorText={new_phone_err}
                    floatingLabelText='手机'
                    defaultValue={default_phone}
                    floatingLabelStyle={{color: blue300}}
                    fullWidth={true}
                    onChange={(e, newValue) => {
                        const phone = newValue;
                        if (phone === '')
                            this.setState({new_phone: phone, new_phone_err: '手机号不可为空'});
                        else if(/^13[0-9][0-9]{8}|15[0-9][0-9]{8}|18[0-9][0-9]{8}$/.test(phone) && phone.length == 11)
                            this.setState({new_phone: phone, default_phone:phone, new_phone_err: ''});
                        else
                            this.setState({new_phone: phone, new_phone_err: '手机号格式错误！'});
                        Meteor.call('registerUser.exist',phone,(err, res)=>{
                            if(err){
                                this.setState({new_phone: phone, new_phone_err: err});
                            }else if(res){
                                this.setState({new_phone: phone, new_phone_err: '手机号已被注册！'});
                            }
                        })
                    }}
                    />
                    <TextField
                    hintText='输入邮箱地址'
                    errorText={new_email_err}
                    defaultValue={default_email}
                    floatingLabelText='邮箱'
                    floatingLabelStyle={{color: blue300}}
                    fullWidth={true}
                    onChange={(e, newValue) => {
                        const email = newValue;
                        if (email === '')
                            this.setState({new_email: email, new_email_err: '邮箱地址不可为空'});
                        else if(/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email))
                            this.setState({new_email: email, default_email:email, new_email_err: ''});
                        else
                            this.setState({new_email: email, new_email_err: '邮箱格式错误！'});
                    }}
                    />
                    <TextField
                    hintText='输入通讯住址'
                    errorText={new_address_err}
                    defaultValue={default_address}
                    floatingLabelText='通讯地址'
                    floatingLabelStyle={{color: blue300}}
                    fullWidth={true}
                    onChange={(e, newValue) => {
                        const addr = newValue;
                        if (addr === '')
                            this.setState({new_address: addr, new_address_err: '通讯地址不可为空'});
                        else
                            this.setState({new_address: addr, default_address: addr, new_address_err: ''});
                    }}
                    />
                    <TextField
                    hintText='输入工作单位名称'
                    errorText={new_unit_err}
                    defaultValue={default_unit}
                    floatingLabelText='工作单位'
                    floatingLabelStyle={{color: blue300}}
                    fullWidth={true}
                    onChange={(e, newValue) => {
                        const unit = newValue;
                        if (unit === '')
                            this.setState({new_unit: unit, new_unit_err: '工作单位不可为空'});
                        else
                            this.setState({new_unit: unit, default_unit:unit, new_unit_err: ''});
                    }}
                    />

                    <Divider style={{border: '0.02px dashed', marginTop: 5, marginBottom: 5}}/>
                    请导入证书文件：
                    <div id='import_form'>
                        <label>证书：</label>
                        <DropZone style={{
                            width: 'auto', height: 'auto', display: 'inline-block', position: 'relative',
                            marginTop: 0, marginLeft: 10, marginRight: 10, marginBottom:30, border:import_cert_border_style
                        }}
                            accept='.cert,.cer'
                            multiple={false}
                            onDrop={this.onDropCertFile.bind(this)}
                        >
                            <div className='import_hint'>{import_cert_file_name != '' ? '已选择文件:' + import_cert_file_name : '点击此处选择文件'}</div>
                        </DropZone>
                    </div>
                </Dialog>
                <Dialog
                    title="证书信息确认提醒"
                    actions={actionCertInfo}
                    modal={false}
                    open={checkPass}
                    onRequestClose={() => {
                        this.setState({ checkPass: false })
                    }}
                >
                    <Divider style={{ border: '1px dashed', marginTop: 2 }} />
                    请注意:<br />
                    1. 请确认证书信息的正确性。<br />
                    2. 证书确认期间可能会对操作带来不便，敬请谅解。
                    <Divider style={{ border: '1px dashed', marginBottom: 30 }} />
                    <p style={{ color: red700 }}>*输入私钥密码:</p>
                    <TextField
                        type='password'
                        floatingLabelText='私钥密码'
                        floatingLabelStyle={{ color: blue400 }}
                        errorText={pass_err}
                        hintText='输入密码'
                        onChange={(e, newValue) => {
                            if (newValue === '')
                                this.setState({ confirmCertInfo: false, user_pass: newValue, pass_err: '密码不可为空' });
                            else
                                this.setState({ confirmCertInfo: true, user_pass: newValue, pass_err: '' });
                        }}
                    />
                </Dialog>
                <Drawer open={check_user_info}
                    width={this.state.check_user_info ? this.state.cw : 0}
                    containerStyle={{ position: 'fixed', top: 0, overflowY: 'hidden' }}
                    openSecondary={true}
                >
                    {this.renderUserInfoCheck()}
                </Drawer>

                <Snackbar
                    open={this.state.snackbar_open}
                    message={this.renderChip()}
                    autoHideDuration={3000}
                    bodyStyle={{ backgroundColor: 'rgba(47,47,47,0.7)', height: 'auto', textAlign: 'center' }}
                    contentStyle={{ height: 80, display: 'inline-block' }}
                    onRequestClose={(reason) => {
                        this.setState({ snackbar_open: !snackbar_open });
                        this.props.handleChange(false);
                        this.setStateByCheck({ check_user_info: !this.state.check_user_info })
                    }}
                />
            </div>
        );
    }
}

RepchainUserRegister.defaultProps = {
    registerUser: true,
}

RepchainUserRegister.childContextTypes = {
    muiTheme: React.PropTypes.object.isRequired,
};


